<template>
  <Card style="width:100%">
    <Row :gutter="20">
      <Col span="6">
      <Cate @cateTreeCompontSelect="cateSelect"></Cate>
      </Col>
      <Col span="18">
      <div>
        <Form :v-model="dataForm" inline>
          <FormItem>
            <Input type="text" v-model="dataForm.key" placeholder="分组名" style="width:200px"></Input>
          </FormItem>
          <FormItem>
            <Button type="success" @click="searchGroup">查询</Button>
            <Button style="margin-left:10px" @click="selectAll">查询全部</Button>
            <Button type="primary" style="margin-left:10px" @click="addGroup">新增</Button>
          </FormItem>
          <Table border :loading="loading" :columns="columns" :data="data">
            <template #action="{ row, index }">
              <Button type="success" size="small" style="margin-right: 5px" @click="showRelation(row)">关联</Button>
              <Button size="small" style="margin-right: 5px" @click="updateGroup(row)">修改</Button>
              <Button type="error" size="small" @click="deleteGroup(row)">删除</Button>
            </template>
          </Table>
          <Row type="flex" justify="end" class="mt_10">
            <Page :current="dataForm.page" :total="total" :page-size="dataForm.limit" @on-change="changePage"
              @on-page-size-change="changePageSize" :page-size-opts="[10, 20, 50]" size="small" show-total show-elevator
              show-sizer></Page>
          </Row>

        </Form>
      </div>
      </Col>
      <!-- 添加或修改分组 -->
      <Modal :title="modalTitle" v-model="modalVisible" @on-cancel="ModalClose" :mask-closable="false" :width="500">
        <Form ref="form" :model="form" :label-width="100">
          <FormItem label="分组名:">
            <Input v-model="form.attrGroupName" placeholder="请输入分组名"></Input>
          </FormItem>
          <FormItem label="排序:">
            <Input v-model="form.sort" placeholder="请输入排序"></Input>
          </FormItem>
          <FormItem label="描述:">
            <Input v-model="form.descript" placeholder="请输入排序"></Input>
          </FormItem>
          <FormItem label="分类:">
            <CateCascader @selected="selectedCate" :cateId="form.catelogId" style="width:200px" />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="modalVisible = false">取消</Button>
          <Button type="primary" :loading="submitLoading" @click="handleSubmit">提交</Button>
        </div>
      </Modal>
      <!-- 查看关联详情 -->
      <Modal :title="relationDetailTitle" v-model="relationDetailVisible" :mask-closable="false" :width="1000">
        <Space direction="vertical">
          <Space wrap>
            <Button type="primary" @click="addRelationShow">添加关联</Button>
          </Space>
        </Space>
        <Table border :columns="columnRelation" :data="RelationData" style="margin-top:10px">
          <template #action="{ row, index }">
            <Button type="success" size="small" @click="removeGroupAttrRelation(row)">移除</Button>
          </template>
        </Table>
      </Modal>
      <!-- 添加关联 -->
      <Modal :title="addRelationTitle" v-model="addRelationVisible" :mask-closable="false" :width="1000">
        <Select v-model="addRelationAttrId" multiple filterable style="width:600px">
          <Option v-for="item in nowGroupNoRelationAttr" :value="item.attrId" :key="item.attrId">{{ item.attrName }}
          </Option>
        </Select>
        <Button type="primary" style="margin-left:10px" @click="addToGroup">添加到当前分组</Button>
      </Modal>
    </Row>
  </Card>

</template>

<script>
import Cate from "@/views/mycomponents/cate.vue"
import CateCascader from "@/views/lili-components/CateCascader.vue"
import * as ApiGroup from "@/api/myapi/Group"
export default {
  name: "goods-group",
  components: { Cate, CateCascader },
  data() {
    return {
      dataForm: {
        key: "",
        cateId: null,
        page: 1,
        limit: 10,
      },
      columns: [
        {
          title: '分组id',
          key: 'attrGroupId'
        },
        {
          title: '组名',
          key: 'attrGroupName'
        },
        {
          title: '排序',
          key: 'sort'
        },
        {
          title: '描述信息',
          key: 'descript'
        },
        {
          title: '所属分类',
          key: 'catelogId'
        },
        {
          title: '操作',
          slot: "action",
          width: 200,
          align: 'center'
        }
      ],
      total: 0,
      data: [],
      loading: true,
      // 对话框标题
      modalTitle: '',
      // 对话框展示
      modalVisible: false,
      // 添加或修改表单
      form: {
        attrGroupName: '',
        sort: 0,
        descript: '',
        catelogId: '',
      },
      // 区分执行的时候是添加还是修改 0:添加 1:修改
      modalType: 0,
      submitLoading: false, // 添加或编辑提交状态
      relationDetailTitle: '关联详情',//查看关联详情标题
      relationDetailVisible: false,//查看关联详情显示
      // 关联详情表的列
      columnRelation: [
        {
          title: 'ID',
          key: 'id'
        },
        {
          title: '属性名称',
          key: 'attrName'
        },
        {
          title: '所属分类',
          key: 'cateLogName'
        },
        {
          title: '操作',
          slot: "action",
          width: 200,
          align: 'center'
        }
      ],
      // 关联详情表的数据
      RelationData: [],
      // 添加关联对话框title
      addRelationTitle: '添加关联',
      // 添加关联对话框显示
      addRelationVisible: false,
      // 从后端获取未被当前分组所关联的属性
      nowGroupNoRelationAttr: [],
      // 现在要添加关联的分组的id
      nowGroupId: null,
      // 添加关联中选再的要拿去添加的attrid
      addRelationAttrId: [],
    }
  },
  methods: {
    init() {
      this.getDataList();
    },
    getDataList() {
      this.loading = true;
      console.log('查看查询参数:', this.dataForm);

      let params = JSON.parse(JSON.stringify(this.dataForm));

      ApiGroup.getAttrGroupByPage(params).then(res => {
        if (res.data.code == 201) {
          this.loading = false;
          this.data = res.data.obj.list;
          this.total = res.data.obj.totalCount
        }
      })
    },
    cateSelect(param) {
      this.dataForm.cateId = param[0].id;
      this.getDataList();
    },

    // 分页 改变页码
    changePage(v) {
      this.dataForm.page = v;
      this.getDataList();
    },
    // 分页 改变页数
    changePageSize(v) {
      this.dataForm.limit = v;
      this.getDataList();
    },
    // 按照输入的关键字查询分组
    searchGroup() {
      this.getDataList();
    },
    // 清除查询数据 请求全部的分组信息
    selectAll() {
      this.dataForm.key = "";
      this.dataForm.cateId = null;
      this.dataForm.page = 1;
      this.dataForm.limit = 10
      this.getDataList();
    },
    // 选择分类
    selectedCate(item) {
      let arr = item[0];
      this.form.catelogId = arr[2]
    },
    // 关闭对话框
    ModalClose() {
      // 清除表单
      this.$refs.form.resetFields();
    },
    // 弹出添加框
    addGroup() {
      console.log('点击添加按钮');
      this.modalType = 0;
      this.modalTitle = "添加";
      this.$refs.form.resetFields();
      this.form.catelogId = null;
      delete this.form.id;
      this.modalVisible = true;
    },
    // 弹出修改分组框
    updateGroup(params) {
      console.log('点击修改按钮测试参数:', params);
      this.modalType = 1;
      this.modalTitle = "修改";

      this.form.attrGroupId = params.attrGroupId;
      this.form.attrGroupName = params.attrGroupName;
      this.form.catelogId = params.catelogId;
      this.form.descript = params.descript;
      this.form.icon = params.icon;
      this.form.sort = params.sort;

      this.modalVisible = true;
    },
    // 提交表单
    handleSubmit() {
      if (this.modalType === 0) {
        // 添加 避免编辑后传入id等数据
        delete this.form.id;
        console.log('测试参数:', this.form);
        ApiGroup.addGroup(this.form).then(res => {
          if (res.data.code == 201) {
            this.$Message.success("操作成功");
            this.getDataList();
            this.modalVisible = false;
          } else {
            this.$Message.error("操作失败");
            this.getDataList();
            this.modalVisible = false;
          }
        })
      } else {
        // 保存/修改操作
        console.log('测试参数:', this.form);
        ApiGroup.editGroup(this.form).then(res => {
          if (res.data.code == 201) {
            this.$Message.success("操作成功");
            this.getDataList();
            this.modalVisible = false;
          } else {
            this.$Message.error("操作失败");
            this.getDataList();
            this.modalVisible = false;
          }
        })
      }
    },
    // 删除分组
    deleteGroup(params) {
      console.log('点击删除分组按钮', params);

      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除分组 " + params.attrGroupName + " ?",
        loading: true,
        onOk: () => {

          ApiGroup.deleteGroup(params.attrGroupId).then(res => {
            this.$Modal.remove();
            if (res.data.code == 201) {
              this.$Message.success("操作成功");
              this.getDataList();
            } else {
              this.$Message.error("操作失败");
              this.getDataList();
            }
          })

        },
      });
    },
    // 展示当前分组关联的属性
    showRelation(params) {
      console.log('点击查看关联:', params);
      this.RelationData = [];
      this.relationDetailVisible = true;
      this.nowGroupId = params.attrGroupId
      // 获取表格数据
      ApiGroup.getAttrGroupRelationByGroupId(params.attrGroupId).then(res => {
        if (res.data.code == 201) {
          this.RelationData = res.data.obj;
        }
      });
    },
    // 展示添加关联对话框
    addRelationShow() {
      // 把之前的对话框关掉
      this.relationDetailVisible = false
      this.addRelationVisible = true;

      // 查询数据
      ApiGroup.getNoRelationAttrByGroupId(this.nowGroupId).then(res => {
        if (res.data.code == 201) {
          this.nowGroupNoRelationAttr = res.data.obj;
        }
      })
    },
    // 添加选中的属性到当前分组
    addToGroup() {
      let params = {};
      params.groupId = this.nowGroupId;
      params.attrIds = this.addRelationAttrId;
      console.log('请求之前测试参数:', JSON.stringify(params));
      ApiGroup.addToGroup(params).then(res => {
        if (res.data.code == 201) {
          this.$Message.success("操作成功");
          this.addRelationVisible = false;
        } else {
          this.$Message.error(res.data.message);
        }
      })
    },
    // 移除attr和分组的关联关系
    removeGroupAttrRelation(row) {
      console.log('点击移除按钮:', row);
      ApiGroup.removeRelation(row.id).then(res => {
        if (res.data.code == 201) {
          this.$Message.success("操作成功");
          this.relationDetailVisible = false;
        } else {
          this.$Message.error(res.data.message);
        }
      })
    }
  },
  created() {
    this.init();
  }
}
</script>

<style>

</style>